import { Injectable } from "@nestjs/common";
import { TaskProgress, TaskStatus } from "./sse-enhance.type";

@Injectable()
export class TaskProgressStore {
    private readonly progressMap = new Map<string, TaskProgress>();

    // Init task
    initTask(taskId: string) {
        if (!this.progressMap.has(taskId)) {
            this.progressMap.set(taskId, {
                taskId,
                progress: 0,
                message: 'Task started',
                status: TaskStatus.IN_PROGRESS,
            })
        }
    }

    // Update Task progress
    updateProgress(taskId: string, progress: number, message?: string): void {
        const task = this.progressMap.get(taskId);
        if (!task) return;

        const newProgress = Math.min(progress, 100);
        const newStatus = newProgress === 100 ? TaskStatus.COMPLETED : TaskStatus.IN_PROGRESS;
        this.progressMap.set(taskId, {
            ...task,
            progress: newProgress,
            message: message || `Working in...${newProgress}%`,
            status: newStatus,
        })

        if (newStatus === TaskStatus.COMPLETED) {
            setTimeout(() => { this.progressMap.delete(taskId); }, 3000);
        }
    }

    // mark special task failed
    markTaskFailed(taskId: string, errorMessage?: string): void {
        const task = this.progressMap.get(taskId);
        if (!task) return;

        this.progressMap.set(taskId, {
            ...task,
            message: errorMessage || 'Task failed',
            status: TaskStatus.FAILED,
        })
        setTimeout(() => {
            this.progressMap.delete(taskId);
        }, 3000);
    }

    // get current task progress
    getTask(taskId: string): TaskProgress | null {
        return this.progressMap.get(taskId) || null
    }

    // delete task
    removeTask(taskId: string): void {
        this.progressMap.delete(taskId);
    }
}